package weaver.interfaces.htsc.hrm;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import weaver.conn.RecordSet;

import weaver.formmode.setup.ModeRightInfo;
import weaver.general.*;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.schedule.BaseCronJob;

import java.text.SimpleDateFormat;
import java.util.*;

public class OrganizationSynTime extends BaseCronJob {
    @Override
    public void execute() {
        //老方法逻辑
//        OrganizationSynTimeOld OrganizationSynTimeOld = new OrganizationSynTimeOld();
//        OrganizationSynTimeOld.initSyn();

        //新逻辑
        initSynNew();
    }

    public void initSynNew()
    {
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        bb.writeLog("OrganizationSyn");
        RecordSet rs = new RecordSet();
        String tbrq = "" ;

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.add(Calendar.DATE, -10);
        tbrq = sdf.format(calendar.getTime());
        bb.writeLog("tbrq:"+tbrq);

        try{
            String sql = " delete from hrmresource_incsyn " ;
            boolean flag = rs.executeUpdate(sql);
            if(flag){
                sql = " insert into hrmresource_incsyn select * from hrmresource ";
                rs.executeUpdate(sql);
            }
        }catch (Exception e){
            bb.writeLog("增量更新失败");
        }

        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
        String createTimeGreater = tbrq+"T"+format2.format(new Date()) ;

        OrganizationTimeSynHrm organizationTimeSynHrm = new OrganizationTimeSynHrm();
        OrganizationTimeSynDept organizationTimeSynDept = new OrganizationTimeSynDept();

        String dept_message = "";
        if(!"".equals(tbrq))
        {
            Map<String,String> headMap = new HashMap<String,String>();
            try {
                OrganizationSyn organizationSyn = new OrganizationSyn();
                String token = organizationSyn.getToken();
                headMap.put("JTXT-AUTH-TOKEN",token);
                headMap.put("JTXT-AUTH-TYPE","APP");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-获取token异常:"+e);
            }

            try{
                bb.writeLog("开始同步部门信息");
                String deptUrl = pb.getPropName("deptUrl_Inc");
                Map<String,String> map = organizationTimeSynDept.doDeptSyn(deptUrl,createTimeGreater,headMap);
                String updatesuccesscount = map.get("updatesuccesscount");
                String updateerrorcount = map.get("updateerrorcount");
                String insertsuccesscount = map.get("insertsuccesscount");
                String inserterrorcount = map.get("inserterrorcount");
                String exceptioncount = map.get("exceptioncount");
                String allcount = map.get("allcount");
                dept_message = "部门同步(增量)总数:"+allcount+",新增成功:"+insertsuccesscount+",新增失败:"+inserterrorcount+",更新成功:"+updatesuccesscount+",更新失败:"+updateerrorcount+",更新异常:"+exceptioncount;

                bb.writeLog("结束同步部门信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            String res_message = "";
            try{
                bb.writeLog("开始同步人员信息");

                updateBelongto();
                String hrmUrl = pb.getPropName("hrmUrl_Inc");

                Map<String,String> map = organizationTimeSynHrm.doHrmSyn(hrmUrl,createTimeGreater,headMap);

                String updatesuccesscount = map.get("updatesuccesscount");
                String updateerrorcount = map.get("updateerrorcount");
                String insertsuccesscount = map.get("insertsuccesscount");
                String inserterrorcount = map.get("inserterrorcount");
                String exceptioncount = map.get("exceptioncount");
                String allcount = map.get("allcount");
                String dataerrorcount = map.get("dataerrorcount");
                res_message = "人员同步(增量)(主岗)总数:"+allcount+",新增成功:"+insertsuccesscount+",新增失败:"+inserterrorcount+",更新成功:"+updatesuccesscount+",更新失败:"+updateerrorcount+",更新异常:"+exceptioncount+",异常数据:"+dataerrorcount;
                bb.writeLog("结束同步人员信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            String pos_message = "";
            try{
                bb.writeLog("开始同步岗位信息");
                String jobUrl = pb.getPropName("jobUrl_Inc");
                Map<String,String> map = organizationTimeSynHrm.doPositionSyn(jobUrl,createTimeGreater,headMap);
                String updatesuccesscount = map.get("updatesuccesscount");
                String updateerrorcount = map.get("updateerrorcount");
                String insertsuccesscount = map.get("insertsuccesscount");
                String inserterrorcount = map.get("inserterrorcount");
                String exceptioncount = map.get("exceptioncount");
                String allcount = map.get("allcount");
                String dataerrorcount = map.get("dataerrorcount");

                pos_message = "人员同步(增量)(兼岗)总数:"+allcount+",新增成功:"+insertsuccesscount+",新增失败:"+inserterrorcount+",更新成功:"+updatesuccesscount+",更新失败:"+updateerrorcount+",更新异常:"+exceptioncount+",异常数据:"+dataerrorcount;
                bb.writeLog("结束同步岗位信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }
            OrganizationSyn OrganizationSyn = new OrganizationSyn();
            try{
                String deptUrl = pb.getPropName("deptUrl_Inc");
                bb.writeLog("开始同步部门领导信息信息");
                doDeptSynToLeader(deptUrl,createTimeGreater,headMap);
                bb.writeLog("结束同步部门领导信息信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }
            OrganizationSynUtil OrganizationSynUtil = new OrganizationSynUtil();
            try{
                bb.writeLog("开始同步部门矩阵信息");
                OrganizationSyn.doMatrixInfo();
                bb.writeLog("结束同步部门矩阵信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            try{
                bb.writeLog("开始设置控件不检测");
                OrganizationSyn.setSysActivexCheck();
                bb.writeLog("结束设置控件不检测");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            try{
                bb.writeLog("开始更新出错的兼岗");
                OrganizationSynUtil.updatePositionStatus();
                bb.writeLog("结束更新出错的兼岗");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            try{
                bb.writeLog("开始更新兼岗从主岗同步的信息");
                OrganizationSynUtil.updatePositionInfo();
                bb.writeLog("开始更新兼岗从主岗同步的信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");//设置日期格式
            String modedatacreatedate = sdfDate.format(new Date());
            String modedatacreatetime = sdfTime.format(new Date());
            String modedatacreatertype = "0";

            String syn_hrmmode_cubeuuid = pb.getPropName("UF_ORGSYNTIME_CUBEUUID");
            JSONObject jsonObject = pb.getModeInfoByUUID(syn_hrmmode_cubeuuid);
            int formmodeid = Util.getIntValue(jsonObject.getString("modeid")) ;
            bb.writeLog("formmodeid:"+formmodeid);

            int userid = 1;
            String modeuuid = UUID.randomUUID().toString();
            String sql = " insert into uf_orgsyntime(tbrq,tbsj,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,modeuuid,bmtbsl,ryzgtbsl,ryjgtbsl)values\n" +
                    " ('"+modedatacreatedate+"','"+modedatacreatetime+"',"+formmodeid+","+userid+","+modedatacreatertype+",'"+modedatacreatedate+"','"+modedatacreatetime+"','"+modeuuid+"','"+dept_message+"','"+res_message+"','"+pos_message+"') ";
            bb.writeLog("sql:"+sql);
            boolean bool = rs.executeUpdate(sql);
            bb.writeLog("bool:"+bool);
            if(bool){
                rs.executeQuery( "select id from uf_orgsyntime where modeuuid='" + modeuuid + "'" );
                while (rs.next()) {
                    int id = Util.getIntValue( rs.getString( "id" ) );
                    ModeRightInfo moderight = new ModeRightInfo();
                    moderight.editModeDataShare(userid, formmodeid, id );
                }
            }
        }
        removeCache();
    }

    /***
     * 部门同步
     * @param url
     */
    public Map<String,String> doDeptSynToLeader(String url,String createTimeGreater,Map<String,String> headMap)
    {
        OrganizationSynUtil OrganizationSynUtil = new OrganizationSynUtil();
        BaseBean bb = new BaseBean();
        bb.writeLog("doDeptSynToLeader");
        int updatesuccesscount = 0;
        int updateerrorcount = 0;
        int exceptioncount = 0;
        Map<String,String> map = new HashMap<String,String>();
        JSONObject jsonObject = new JSONObject();
        bb.writeLog("createTimeGreater:"+createTimeGreater);
        jsonObject.put("createTimeGreater",createTimeGreater);
        String response = OrganizationSynUtil.sendPost(url,jsonObject.toJSONString(),headMap);
//默认所有部门挂在华泰集团这个分部下
        RecordSet rs = new RecordSet();
        JSONArray deptArray = JSONArray.parseArray(response);
        for(int i=0;i<deptArray.size();i++)
        {
            JSONObject deptJson = deptArray.getJSONObject(i);
            String deptCode = deptJson.getString("deptCode");//部门编码
//部门HRBP转换对应人员的ID
            String deptHrBP = Util.null2String(deptJson.getString("deptHrBP"));//部门HRBP //主账号
            JSONArray deptHrBp2Arr = deptJson.getJSONArray("deptHrBp2");//部门HRBP2 //主账号
            deptHrBp2Arr.add(deptHrBP);
            deptHrBP = OrganizationSynUtil.getUserIdsByCodes(deptHrBp2Arr);
            String deptMP = Util.null2String(deptJson.getString("deptMP"));//部门内勤
            deptMP = OrganizationSynUtil.getUserIdByCode2Main(deptMP);  //主账号
            JSONArray deptDirectorsArr = deptJson.getJSONArray("deptDirectors");//部门负责人
            JSONArray deptLeadersArr = deptJson.getJSONArray("deptLeaders");//部门分管领导  //主账号
            try{
                String deptId = getDeptIdByCode(deptCode);
                String deptDirectors = OrganizationSynUtil.getUserIdsByCodes2Dept(deptDirectorsArr);
                String deptLeaders = OrganizationSynUtil.getUserIdsByCodesObj(deptLeadersArr);
                String cohead = OrganizationSynUtil.getCohead(deptDirectorsArr);
                String txqyfzr ="";
                try{
                    JSONArray departmentAreaManagers = deptJson.getJSONArray("departmentAreaManagers");//投行区域负责人
                    txqyfzr = OrganizationSynUtil.getUserIdsByCodesObj(departmentAreaManagers); //主账号 多人
                }catch (Exception e){
                    bb.writeLog("OrganizationSyn-e:"+e);
                }

                String deptNum = Util.null2String(deptJson.getString("deptNum")); //部门ID
                int intdeptNum = 0;
                try{
                    if(!"".equals(deptNum)){
                        intdeptNum = Util.getIntValue(deptNum);
                    }else{
                        intdeptNum = -1;
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    intdeptNum = -2;
                }
                if(intdeptNum >0)
                {
                    String deptDefinedId = getDeptDefineidByDeptid(deptId);
                    if(!"".equals(deptDefinedId))
                    {
                        rs.writeLog(deptDefinedId+":"+deptLeaders+":"+deptHrBP+":"+deptMP+":"+deptDirectors+" :update");
                        String deptUpdateSql = " update hrmdepartmentdefined set deptHrBP=?,deptMP=?,deptDirectors=?,deptLeaders=?,cohead=?,txqyfzr=? where id=? ";
                        boolean flag1 = rs.executeUpdate(deptUpdateSql,new Object[]{deptHrBP,deptMP,deptDirectors,deptLeaders,cohead,txqyfzr,deptDefinedId});
                        if(flag1){
                            updatesuccesscount++;
                        }else{
                            updateerrorcount++;
                        }
                    }
                }
                //更新部门自定义字段信息
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
                e.printStackTrace();
                exceptioncount++;
                rs.writeLog("部门编号为"+deptCode+"的数据同步失败，data:"+deptJson.toJSONString());
            }
        }
        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        return map;
    }

    /**
     * 岗位同步
     * @param positionJson
     */
    public void doJobTitleSyn(JSONObject positionJson)
    {

        BaseBean bb = new BaseBean();
        bb.writeLog("-----doJobTitleSyn-----");
        if(positionJson!=null)
        {
            RecordSet rs = new RecordSet();
            String jobtitlecode = positionJson.getString("positionCode");//岗位编码
            String jobtitlename = positionJson.getString("positionName");//岗位名称
            String deptCode = positionJson.getString("deptCode");//部门编码
            bb.writeLog("岗位编码:"+jobtitlecode+",jobtitlename:"+jobtitlename+",部门编码:"+deptCode);
            if(!"".equals(deptCode) && !"".equals(jobtitlecode) && jobtitlecode !=null)
            {
                String deptId = getDeptIdByCode(deptCode);
                bb.writeLog(deptId);
                if(!"".equals(deptId))
                {
                    String jobTitlecId = getJobTitleIdByCode(jobtitlecode,deptId);
                    bb.writeLog(jobTitlecId);
                    if(!"".equals(jobTitlecId) && jobTitlecId !=null)
                    {

                        if(!"".equals(jobtitlecode) && jobtitlecode !=null)
                        {
                            bb.writeLog("update hrmjobtitles");
                            String jobtitleUpateSql = " update hrmjobtitles set jobtitlemark=?,jobtitlename=?,jobdepartmentid=? where id=? ";
                            rs.executeUpdate(jobtitleUpateSql,new Object[]{jobtitlename,jobtitlename,deptId,jobTitlecId});
                        }
                    }else{

                        if(!"".equals(jobtitlecode) && jobtitlecode !=null)
                        {
                            bb.writeLog("insert into hrmjobtitles");
                            String jobtitleInsertSql = " insert into hrmjobtitles(jobtitlemark,jobtitlename,jobdepartmentid,jobtitlecode) values(?,?,?,?)";
                            rs.executeUpdate(jobtitleInsertSql,new Object[]{jobtitlename,jobtitlename,deptId,jobtitlecode});
                        }
                    }
                }
            }
        }
    }



    /**
     * 根据岗位编码和部门ID获取岗位ID
     * @param jobTitleCode
     * @param deptId
     * @return jobTitlecId
     */
    public String getJobTitleIdByCode(String jobTitleCode,String deptId){
        String jobTitlecId = "";
        RecordSet rs = new RecordSet();
        if(!"".equals(jobTitleCode) && !"".equals(deptId)){
            rs.executeQuery(" select id from hrmjobtitles where jobtitlecode=? and jobdepartmentid=? ",new Object[]{jobTitleCode,deptId});
            if(rs.next()){
                jobTitlecId = Util.null2String(rs.getString("id"));
            }
        }
        return jobTitlecId;
    }


    /**
     * 根据部门编码查询部门ID
     * @param deptcode
     * @return deptId
     */
    public String getDeptIdByCode(String deptcode){
        String deptId = "";
        if(deptcode!=null && !"".equals(deptcode))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmdepartment where departmentcode=? ",new Object[]{deptcode});
            if(rs.next())
            {
                deptId = Util.null2String(rs.getString("id"));
            }
        }
        return deptId;
    }

    /**
     * 根据分部编码查询分部ID
     * @param subcompanyCode
     * @return deptId
     */
    public String getSubcomIdByCode(String subcompanyCode)
    {
        String subcomId = "";
        if(subcompanyCode!=null && !"".equals(subcompanyCode))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmsubcompany where subcompanycode=? ",new Object[]{subcompanyCode});
            if(rs.next())
            {
                subcomId = Util.null2String(rs.getString("id"));
            }
        }
        return subcomId;
    }

    /**
     * 根据部门ID获取自定义信息ID
     * @param deptId
     * @return
     */
    public String getDeptDefineidByDeptid(String deptId){
        String deptDefineId = "";
        if(deptId !=null && !"".equals(deptId))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmdepartmentdefined where deptid=? ",new Object[]{deptId});
            if(rs.next()){
                deptDefineId = Util.null2String(rs.getString("id"));
            }
        }
        return deptDefineId;
    }

    /**
     * 获取用户自定义数据的ID
     * @param userId
     * @param scopeid
     * @return
     */
    public int getCusFielddataId(String userId,int scopeid){
        int cusFielddataId = -1;
        if(!"".equals(userId))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select seqorder from cus_fielddata where scopeid=? and id=? ",new Object[]{scopeid,userId} );
            if(rs.next()){
                cusFielddataId = rs.getInt("seqorder");
            }
        }
        return cusFielddataId;
    }

    /**
     * 清除缓存
     */
    public void removeCache(){
        ResourceComInfo resComInfo;
        DepartmentComInfo deptComInfo;
        JobTitlesComInfo jobTitlesComInfo;
        try {
            resComInfo = new ResourceComInfo();
            resComInfo.removeResourceCache();
            deptComInfo = new DepartmentComInfo();
            deptComInfo.removeCompanyCache();
            jobTitlesComInfo = new JobTitlesComInfo();
            jobTitlesComInfo.removeCache();
        } catch (Exception e) {
            new BaseBean().writeLog("OrganizationSynTime-Exception-:"+e);
        }
    }

    /***
     *
     */
    public void updateBelongto(){
        BaseBean bb = new BaseBean();
        try {
            RecordSet rs = new RecordSet();
            String sql = "update hrmresource set belongto=null where status=1 and belongto = -1";
            rs.executeUpdate(sql);
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
        }
    }

}
